package com.hmall.item.servicr.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.servicr.ItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.List;

/**
 * @author 29143
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品信息
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageDTO<Item> findAllByPage(Integer page, Integer size) {

        Page<Item> pages = new Page<>(page, size);

        LambdaQueryWrapper<Item> wrapper = Wrappers.lambdaQuery(Item.class);

        Page<Item> itemPage = itemMapper.selectPage(pages, wrapper);

        List<Item> list = itemPage.getRecords();

        return new PageDTO<>(itemPage.getTotal(),list);

    }

    /**
     * 根据id查询商品信息
     * @param id
     * @return
     */
    @Override
    public Item findById(Long id) {

        Item item = itemMapper.selectById(String.valueOf(id));

        return item;
    }

    /**
     * 添加商品信息
     * @param item
     */
    @Override
    public void addItem(Item item) {
        itemMapper.insert(item);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,item.getId());
    }

    /**
     * 修改商品状态码
     * @param id
     * @param status
     */
    @Override
    public void updateItemStatus(Long id, Integer status) {

        if (status==1){
            itemMapper.updateStatus(id,1);
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,id);

        }
        if (status==2){
            itemMapper.updateStatus(id,2);
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_DELETE_KEY,id);

        }
    }

    /**
     * 修改商品信息
     * @param item
     */
    @Override
    public void updateItem(Item item) {
        itemMapper.updateById(item);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,item.getId());
    }

    /**
     * 根据id删除商品信息
     * @param id
     */
    @Override
    public void deleteItem(Long id) {
        itemMapper.deleteById(id);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_DELETE_KEY,id);
    }


}
